<template>
	
	<view class="groupRoom_body">
		<!-- 聊天区域 -->
		<scroll-view  class="groupRoom_chat_body" scroll-y="true" scroll-with-animation="true" :scroll-into-view="scrollToView">
			<view class="chat-main" :style="{paddingBottom:inputh+'px'}">
			    <view class="chat-ls">
					<view v-for="(message,i) in lobbyMessages.showMessages" :key="i">
						<view class="chat-time" v-show="i==0 || btwnSeconds(lobbyMessages.showMessages[i-1].time,lobbyMessages.showMessages[i].time) > 300">
							{{btwnDays(message.time,getNowTime())==0?message.time.substr(11,5):message.time.substr(0,16)}}
						</view>
						<view :class="['msg-m',message.id!=user.id?'msg-left':'msg-right']">
						    <image class="user-img" @tap="toPersonInfo(message.id)" src="../../static/logo.png"></image>
							<view class="content">
								<view class="nickname">
									<text :class="[message.id!=user.id?'left':'right']">{{message.nickName}}</text>
								</view>
								<view class="message">
									<!-- 文字 -->
								    <view class="msg-text" v-show="message.msgType=='text'">
										<rich-text class="rich-text" :nodes="replaceEmoji(message.content)"></rich-text>
									</view>
									<view class="message" v-show="message.msgType=='image'">
									    <!-- 图像 -->
									    <image :src="message.content" class="msg-img" @tap="showPic(message.content)" mode="widthFix"></image>
									</view>
								</view>
							</view>
						</view>
					</view>
			        
			    </view>
			</view>
		</scroll-view>
		<!-- 输入框 -->
		<view class="groupRoom_body_input">
			<image @tap="turnEmojiShow()" class="icon" src="@/static/emoji.png"></image>
			<textarea  class="content"  @keyup.enter="sendMessge()" v-model="textMsg" maxlength="-1" auto-height />
			<button class="btn" :disabled="disable" :class="{'disabled': disable}" @tap="sendMessge()">发送</button>
		</view>
		
		<!-- emoji表情模块 -->
		<scroll-view v-show="showEmoji" class="emoji-table" >
			<view class="btns">
				<text class="btn" @tap="lastEmojiPage()" v-show="emoji_start!=0">上一页</text>
				<text class="btn" @tap="nextEmojiPage()" v-show="emoji_start!=3">下一页</text>
				<text @tap="turnEmojiShow()" class="btn">关闭</text>
			</view>
			<image v-for="(emoji,pid) in emojis" :key="pid" class="emoji" mode="widthFix" :src="'/static/img/emoji/' + emoji.url"
				 @tap="addEmoji(emoji)">
		</scroll-view>
		
		<!-- 待发送的图片 -->
		<scroll-view v-show="showImage" class="image-table" >
			<view class="btns">
				<text @tap="imageEnsure()" class="btn">发送</text>
				<text @tap="imageCancel()" class="btn">取消</text>
			</view>
			<image class="selecting-image" :src="selecting_image"></image>
		</scroll-view>
		
	</view>
	
</template>

<script>
	import $store from '@/store/index.js';
	import dateUtil from 'util/date';
	import Emojis from '@/common/emojis.js';
	import WebSocket from '@/common/websocket.js';
	import Util from '@/common/util.js';
	import {mapGetters,mapActions,mapMutations} from 'vuex';
	export default{
		data(){
			return{
				//有没有发送过新的消息
				texted:false,
				//控制发送键能够按下
				disable:true, 
				// 输入的聊天内容
				textMsg: '',
				//表情定义
				showEmoji: false,
				//关于发送图片
				showImage:false,
				//待发送的照片
				selecting_image:'',
				emoji_start: 0,
				emojis:[],
				scrollToView: '',
				inputh: '60',
				messages:[],
				showMessages:[],
				sh:'',
				index:0,
			}
		},
		computed:{
			...mapGetters(['user','sessions','lobbyMessages']),
		},
		watch: {
			//监听text，当他有值时发送按钮才可以点击
			textMsg(newVal) {
				if (newVal.trim() != '') {
					this.disable = false
				} else {
					this.disable = true
				}
			},
			// messages(){
			// 	this.messages = this.lobbyMessages.messages;
			// }
		},
		// 初始化加载
		onLoad(options){
			this.setSessionIndex(options.index);
			this.index = options.index;
			// 加载表情
			this.emojis = Util.copySubList(Emojis,0,36);
			// 判断如果id为空则跳转登录，否则开启websocket会话
			if(uni.getStorageSync('id')===null){
				this.monitor()
			}
			$store.state.toUId = 2
			WebSocket.connectSocketInit();
			this.sh = setInterval(this.messageAssignment,500);
			
		},
		methods:{
			messageAssignment(){
				this.messages = this.lobbyMessages.messages;
				if(this.lobbyMessages.messages.length>20){
					this.lobbyMessages.showMessages = this.lobbyMessages.messages.slice(this.lobbyMessages.messages.length-20,this.lobbyMessages.messages.length);
					this.messageIndex = this.lobbyMessages.messages.length - 20;
					clearInterval(this.sh)
				}else{
					this.lobbyMessages.showMessages = this.lobbyMessages.messages; //否则
					console.log(this.lobbyMessages.showMessages)
					this.messageIndex = 0;
					clearInterval(this.sh)
				}
			},
			...mapMutations(['setSessionIndex']),
			...mapActions(['sendMessageOut','reRangeSession']),
			//默认加载监听，判断是否输入账号
			monitor(){
				this.$myRequest({
					url:'/monitor/getmonitor'
				})
			},
			//显示 关闭emoji
			turnEmojiShow() {
				if(this.showImage){
					this.imageCancel();
				}
				this.showEmoji = !this.showEmoji;
				this.emoji_start = 0;
			},
			//emoji翻页
			nextEmojiPage(){
				this.emoji_start ++;
				this.emojis = Util.copySubList(Emojis,this.emoji_start*36,36);
			},
			lastEmojiPage(){
				this.emoji_start --;
				this.emojis = Util.copySubList(Emojis,this.emoji_start*36,36);
			},
			//添加表情
			addEmoji(em) {
				this.textMsg += em.alt;
			},
			replaceEmoji(text){
				return Util.replaceEmoji(text);
			},
			//取消发送照片
			imageCancel(){
				this.showImage = false;
				this.selecting_image = '';
			},
			//显示 关闭emoji
			turnEmojiShow() {
				if(this.showImage){
					this.imageCancel();
				}
				this.showEmoji = !this.showEmoji;
				this.emoji_start = 0;
			},
			//划到底部
			goPageBottom(){
				uni.pageScrollTo({
					scrollTop: 99999999999,    //滚动到页面的目标位置（单位px）
				});
			},
			// 发送聊天内容
			sendMessge(){
				//#ifdef H5
					this.textMsg = this.textMsg.replaceAll('\n','');
				//#endif 
				if(this.textMsg==''||this.textMsg==' '||this.textMsg.length==0){
					return;
				}
				if(this.showEmoji){
					this.turnEmojiShow();
				}
				if(this.showImage){
					this.imageCancel();
				}
				if(this.textMsg.length>100){
					uni.showToast({
						title:'内容不能超过100个字哦~',
						icon:'none',
						mask:false,
						duration:1000
					})
				}else{
					// 获取发送消息的时间
					let time = dateUtil.getTimeNow();
					// 将所需的内容封装进outMessage里
					let outMessage = {
						type:this.message_type,
						message:{
							msgType: 'text',//消息类型
							time:time,
							content:this.textMsg,
							id:uni.getStorageSync('id'),
							nickName:uni.getStorageSync('nickName'),
							avatarId:uni.getStorageSync('avatarId')
						}
					}
					// 发送给服务器
					WebSocket.sendMessage(outMessage);
					// 有发送过消息
					this.texted = true;
					// 将输入款的内容清空
					this.textMsg = '';
					// 滑动栏滚动最低（当前聊天的位置）
					this.goPageBottom();
				}
			},
			btwnSeconds(time1,time2){
				return dateUtil.TimeDifferenceSeconds(time1,time2);
			},
			btwnDays(time1,time2){
				return dateUtil.TimeDifference(time1,time2);
			},
			getNowTime(){
				return dateUtil.getTimeNow();
			}
		},
		
	}
</script>

<style>
	.groupRoom_body{
		width: 100%;
		height: 858px;
		
	}
	.groupRoom_chat_body{
		width: 100%;
		height: 800px;
		background-color: #F1F2F6;
	}
	.groupRoom_body_input{
		border-top: 3px solid #DCE0E3;
		width: 100%;
		height: 58px;
		background-color: #F1F2F6;
		overflow: hidden;
	}
	.icon{
		width: 40px;
		height: 40px;
		margin-left: 10px;
		margin-top: 10px;
		float: left;
	}
	.disabled {
		background-color: #aae8f5;
	}
	.btn {
		width: 56px;
		margin-top: 10px;
		background-color: #55aaff;
		color: white;
		padding: 5px;
		font-size: small;
		margin-left: 10rpx;
		border-radius: 10rpx;
		float: left;
	}
	.btns{
		display: flex;
	}
	.image-table{
		   /*开启弹性布局*/
		display:flex;
		    /*wrap：换行，第一行在上方。*/
		flex-wrap:wrap;
		    /*居中对齐 每个项目两侧的间隔相等*/
		/* justify-content:space-around; */
		  /*或者使用 两端对齐，项目之间的间隔都相等。*/
		justify-content:space-between;
		max-width: 400rpx;
		max-height: 500rpx;
		position: fixed;
		z-index: 10;
		background-color: #f8fff2;
		padding: 5rpx;
		border-radius: 10rpx;
		bottom: 100rpx;
		left: 130rpx;
	}
	.emoji-table{
		   /*开启弹性布局*/
		display:flex;
		    /*wrap：换行，第一行在上方。*/
		flex-wrap:wrap;
		    /*居中对齐 每个项目两侧的间隔相等*/
		/* justify-content:space-around; */
		  /*或者使用 两端对齐，项目之间的间隔都相等。*/
		justify-content:space-between;
		max-width: 500rpx;
		max-height: 300rpx;
		position: fixed;
		z-index: 10;
		background-color: #f8fff2;
		padding: 5rpx;
		border-radius: 10rpx;
		bottom: 100rpx;
		left: 130rpx;
	}
	.selecting-image{
		width: 500rpx;
		height: 600rpx;
	}
	.emoji{
		width: 50rpx;
		height: 50rpx;
		margin: 2rpx;
	}
	.content{
		display: block;
	}
	.chat-main{
		padding-left: 32rpx;
		padding-right: 32rpx;
		padding-top: 20rpx;
		// padding-bottom: 120rpx;  //获取动态高度
		display: flex;
		flex-direction: column;
	}
	.chat-ls .msg-m {
	   display: flex;
	   padding: 20rpx 0;	 	   
	}   
	.chat-ls .msg-img {
	    max-width: 400rpx;
	    border-radius: 20rpx;
	}
	.chat-time {
	    font-size: 24rpx;
	    color: rgba(39, 40, 50, 0.3);
	    line-height: 34rpx;
	    padding: 10rpx 0rpx;
	    text-align: center;
	}
	.user-img {
	    flex: none;
	    width: 100rpx;
	    height: 100rpx;
	    border-radius: 20rpx;
	}
	.content {
	    height: 100%;
	    background-color: rgba(244, 244, 244, 1);
	}
	.nickname{
		margin-left: 10px;
		text-align: right;
		display: flex;
	}
	.nickname .left{
	    text-align: right;
		float: right;
		margin-right: 10rpx;
		font-size: smaller;
	}
	.nickname .right{
	    text-align: right;
		margin-left: auto;
		margin-right: 20rpx;
		font-size: smaller;
	}
	.message {
	    flex: none;
	    max-width: 480rpx;
	}
	.msg-text {
	    font-size: 32rpx;
	    color: rgba(39, 40, 50, 1);
	    line-height: 44rpx;
	    padding: 18rpx 24rpx;		 
	}
	.chat-ls .msg-img {
	    max-width: 400rpx;
	    border-radius: 20rpx;
	}
	.msg-left .msg-text {
		flex-direction: row;
	    margin-left: 16rpx;
	    background-color: #fff;
	    border-radius: 0rpx 20rpx 20rpx 20rpx;
	}
	.msg-right .msg-text {
		flex-direction: row-reverse;
	    margin-right: 16rpx;
	    background-color: rgba(85, 170, 255, 0.8);
	    border-radius: 20rpx 0rpx 20rpx 20rpx;
	}	 
	.msg-left .msg-img {
		flex-direction: row;
	    margin-left: 16rpx;
	}
	
	// 底部输入款样式
	.groupRoom_body_input .content{
			width: 70%;
			box-sizing: border-box;
			margin-top: 10px;
			background-color: #FFFFFF;
			border-radius: 30rpx;
			padding: 16rpx;
			caret-color: #01B4FE;
			float:left;
		}
</style>